<template>
  <view class="w-full h-full g-theme-bg">
    <!-- 首页 -->
    <home v-show="toPage.page == 'home'" ref="homeRef"></home>
    <!-- 待办 -->
    <todo v-show="toPage.page == 'todo'" ref="todoRef"></todo>
    <!-- 我的 -->
    <my v-show="toPage.page == 'my'" ref="myRef"></my>

    <f-tabbar v-model:current="toPage.page" :tabbarList="tabbarList" @change="switchTabbar"></f-tabbar>
  </view>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import Home from './components/home/index.vue'
import Todo from './components/todo/index.vue'
import My from './components/my/index.vue'

const toPage = ref({})

const homeRef = ref()
const todoRef = ref()
const myRef = ref()

const tabbarList = [
  {
    page: 'home',
    text: '首页',
    iconPath: '/static/tabbar/home.png',
    selectedIconPath: '/static/tabbar/home-active.png',
    isKeepAlive: true,
    ref: homeRef,
  },
  {
    page: 'todo',
    text: '待办',
    iconPath: '/static/tabbar/todo.png',
    selectedIconPath: '/static/tabbar/todo-active.png',
    isKeepAlive: false,
    ref: todoRef,
  },
  {
    page: 'my',
    text: '我的',
    iconPath: '/static/tabbar/my.png',
    selectedIconPath: '/static/tabbar/my-active.png',
    isKeepAlive: true,
    ref: myRef,
  },
]

let keepAliveList = []
let fromPage = ''

const switchTabbar = (item) => {
  if (item.isKeepAlive) {
    if (keepAliveList.includes(item.page)) {
      item.ref.value.active()
    } else {
      keepAliveList.push(item.page)
      item.ref.value.showPage()
    }
  } else {
    item.ref.value.showPage()
  }
  if (!fromPage.isKeepAlive) {
    fromPage.ref.value.hidePage()
  }
  fromPage = { ...item }
}

const init = () => {
  // 初始化
  toPage.value = { ...tabbarList[0] }
  if (tabbarList[0].isKeepAlive) {
    keepAliveList.push(tabbarList[0].page)
  }
  fromPage = { ...tabbarList[0] }
  nextTick(() => {
    fromPage.ref.value.showPage()
  })
}

onMounted(() => {
  init()
})

onShow(() => {
  init()
})
</script>
